package com.zimmor.hq.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zimmor.hq.entity.AppCookie;
import com.zimmor.hq.util.*;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Base64;

@Service
public class HqService {
    public static String deviceid = "02c31d72a492af119ab112caf6a062754585";
    public static String APPToken = "eyJlIjoxNzExMzQ5ODM0LCJkIjoiZDIxZjIyMjZmNGNlMjNiMmM1MTgyNzRmNmM5ODQ4MWMiLCJ1IjoiM2NjMjY4MTAwMzlkMjQwY2Q3NmIxNzEyYjU3ZDJkYzQ2MmY1NmJmNmUzZWZiY2I3YzJmMDk2MzAwNDYwMTVlMyIsInAiOjAsInQiOiJhcHAiLCJvIjoiQW5kcm9pZCJ9.22f3700eecf8bd2687a1abd49eac269b848ff5fdfd6194a187c6bbd0632ce359";

    public  String username = "1193776794";
    public  String password = "13593117257";
    public static void main(String[] args) {

        HqService hqService = new HqService();
        String token = "b4b439fc497647938b63e4c21b925f04";
//        String name = "尹颖怡";
//        String idCard = "F4A4F644C5E125845A5C8C71E84FF5D30EF781A53BE46A5D42A32BD17B22D7A6";

//        String name = "尹颖怡";
        String userId = "65c87bbcf1738b6b534d75c2";
        hqService.order(userId);
//        id_card = "f4a4f644c5e125845a5c8c71e84ff5d30ef781a53be46a5d42a32bd17b22d7a6"
//        hqService.saveUser(name, idCard);
//        hqService.getUser();
//        hqService.operateCode();
//        hqService.verifyOperateCode("136752", "9b87d8e833af999926d84732ebd604b4H6n3XJE4tJ6");
//        hqService.setPwd("Hq123457", "f4e3f41275bc6ca6e71d951560906c9331huVecLDuZ");
//        String string = hqService.generateRandomString(32);
//        String s = hqService.generateRandomDigits(10);
//        System.out.println("s = " + s);
//        System.out.println("string = " + string);
//          String phone = "13098358616";
//        hqService.sendCode("07d047d41be1583b43040541f51aed347f9e", hqService.getTime(), phone);
//        String ticket = "tr03ferrIoOIdmlBUqvAuTqaMo2GkCLNhBr9vHJPBXu0zNEgaabPz08Pms8EH49aPiVv0nHCMz7cp6R4OaQt_RDQvmwLlB7elY4cJivd3tj5OzyYln3LFwpWBw**";
//        String randstr ="@6eX";
//        String formattedTime = hqService.getTime();
//        String sendImgCodeResult = hqService.sendImgCode(deviceid, formattedTime, phone, ticket, randstr);
//        System.out.println("sendImgCodeResult = " + sendImgCodeResult);
//          String phone = EomsgUtil.getPhone(token);
//          System.out.println("phone = " + phone);
//        String phone = "13151445772";
//        String urlEncode = "%E5%8C%97%E4%BA%AC%E7%8E%AF%E7%90%83%E5%BA%A6%E5%81%87%E5%8C%BA";
//        String msg = EomsgUtil.getMsg(token, phone, "北京环球度假区");
//        System.out.println("msg = " + msg);
//        hqService.getDeviceInfo();
//        String appid = "unibank10044";
//        String userId = "611715375293473139";
//        String outTradeNo = "B,PU000000T7CX7";
//        hqService.openSave(appid, userId, outTradeNo);
//        hqService.payment(userId);
//        JSONObject jsonObject = JSON.parseObject("{\"retCode\":0,\"msg\":\"\",\"token\":\"00e65c48d0461ef0e66fe54de1aa0842c1cb\",\"data\":\"WDuGmhM/Hz0h+ap9OnD7vnjSOkEBcuMDyZFFfYPc9gDEQVuwoh4PZ/W1LwRwRRnCRLQysuelWjwZ6c9dVwux30xUaLmValGXdmyuU50WFt2S0/vazSQb/SXO1OrkzgTETIccIpqRdXBFE50aQiEbvmokxkqb1UxguT44vCTVf9Vl56aeoqEhvBkDW/kbryVOgyFb2onTruJlU5kMgxO1k4drwG/rmVNbplAV51t0lbZA1b8qjV6dDBzolADeawza72vrf1yY4lKvbV/YQJIElMbq9WeY2D3juthjyjb6Hwrd827xhsxBfUMjtu0kG8UmwYcfdSU34e4iHMKRhxEzKWB6U/rY0FKVIV0ifrmFHt9e+HMvVm5T32A1cbZQofqQsSX/0Ff4TDoU8thsiNh4t1/r7YH9bm6CIyhagdCb1KL1OXuH4blyxg7RAuGgBr/5dWD2KzK8L4rCNYaD+ptnJ7pneHDEz5MneG3rWn1ncxulI+Z8FPkkeQ9yYGn+UIF3ox2ePw1B7nZhBM7PgsUtfdTbEW/qz3JBmJsrwxUIjMZT2pfoVEQYu/SrH34EoUZaZk6l9eCVk0yCnGXJYAW+ssCckLZqoV68HEr6NHxyQ6MuZsW2CCzwTzNfAxleMuvWdCle9ILl/HUBub1waeLeD37Fk1JKjf0xkSORxf7270DbEuRvCniDOfHnh2bgGyhJ03tIrF0E/QueBLpI/hvEkal/r9MkF15u/g9L9eqRHkenkVlXza9G5Ypog8Ui\",\"seq\":0}");
//        System.out.println(" ================ ");
//        System.out.println(jsonObject.get("token"));
//        AppCookie cookie = hqService.createCookie();
//        System.out.println("cookie = " + cookie.toString());
    }

    public void createOrder() {
        //获取token
        String deviceid = "";
        String APPToken = "";
        //添加信息
        String name = "";
        String idCardNum = "";
        String idCard = IdCardEncodeUtil.encodeIdCardNum(idCardNum);
        JSONObject json = saveUser(name, idCard);
        JSONObject data =(JSONObject) json.get("data");
        String userId = CommonUtil.getJsonValue(data, "_id");
        String orderInfo = order(userId);
        //用订单信息拉起支付，获取支付链接
    }

    public AppCookie createCookie() {
        String deviceInfo = getDeviceInfo();
        JSONObject json = JSON.parseObject(deviceInfo);
        String deviceid = json.get("token").toString();
        String formattedTime = getTime();
        String token = EomsgUtil.login(username, password);
        String phone = EomsgUtil.getPhone(token);
        String sendCodeResult = sendCode(deviceid, formattedTime, phone);
        JSONObject jsonObject = JSON.parseObject(sendCodeResult);
        String fid = null;
        Boolean flag = (Integer) jsonObject.get("ret") == 1;
        if(flag) {
            //todo 调用dll
            String ticket = "t03toKLmET4Kas_r_CGqXevRJkYZG3ufr_8k4onyknJuMxlotVDh5wTbrIIxMlgpmHhrNsMhhdRfpcEUqjT-AumGHHxunb5MY-WEb0y9R2okJTOy99VmYfgGDAU1BY5vaG6MX-54chQxyY*";
            String randstr ="@mBf";
            formattedTime = getTime();
            String sendImgCodeResult = sendImgCode(deviceid, formattedTime, phone, ticket, randstr);
            JSONObject json1 = JSON.parseObject(sendImgCodeResult);
            if((Integer) json1.get("ret") == 0) {
                JSONObject data = (JSONObject) json1.get("data");
                fid = (String) data.get("fid");
            } else {
                return null;
            }
        } else if((Integer) jsonObject.get("ret") == 0) {
            Map<String, String> map = (Map) jsonObject.get("data");
            fid =  map.get("fId");
        }
        formattedTime = getTime();
        String keyWord = "";
        String msg = EomsgUtil.getMsg(token, phone, keyWord);
        String code = CommonUtil.extractVerificationCode(msg);
        String loginCodeResult = loginCode(deviceid, formattedTime, fid, phone, code);
        JSONObject json2 = JSON.parseObject(loginCodeResult);
        JSONObject data = (JSONObject) json2.get("data");
        String appToken = (String) data.get("token");
        AppCookie appCookie = new AppCookie();
        appCookie.setDeviceid(deviceid);
        appCookie.setAppToken(appToken);
        return appCookie;
    }
    public String getUser() {
        String formattedTime = getTime();
//        String formattedTime = "Tue, 20 Feb 2024 08:52:26 GMT";
        String message = "x-date: "+formattedTime+"\n" +
                "GET\n\n\n\n" +
                "/v2/guest/list?type=place_order";
        String signature = hmacsha1(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", "hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"" + signature + "\"");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/guest/list";
        Map<String, String> params = new HashMap<>();
        params.put("type", "place_order");
        String response = OkHttpUtil.get(url, params, headers);
        System.out.println(response);
        return response;
    }

    public JSONObject saveUser(String name, String idCard) {
        String formattedTime = getTime();
//        String formattedTime = "Tue, 20 Feb 2024 12:20:04 GMT";
//        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/guest/save?card_type=1&guest_type&id&id_card=%s&is_confirm=0&name=%s", formattedTime, idCard, name);
        String message = "x-date: "+formattedTime+"\n" +
                "POST\n\n\n\n" +
                "/v2/guest/save?card_type=1&guest_type&id&id_card="+idCard+"&is_confirm=0&name="+name;
        String signature = hmacsha1(message);
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", "hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"" + signature + "\"");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/guest/save";
        Map<String, String> params = new LinkedHashMap<>();
        params.put("id", "");
        params.put("name", name);
        params.put("card_type", "1");
        params.put("id_card", idCard);
        params.put("guest_type", "");
        params.put("is_confirm", "0");
//        String jsonParam = JSON.toJSONString(params);
        String response = OkHttpUtil.postParamsInPath(url, headers, params);
//        System.out.println(response.getText());
        System.out.println(response);
        JSONObject result = null;
        try {
            result = JSONObject.parseObject(response);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("保存游客信息结果获取失败");
        }
        return result;
    }

    public String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5Hash = md.digest(input.getBytes());
            String md5Hex = bytesToHex(md5Hash);
            byte[] base64Encoded = Base64.getEncoder().encode(md5Hex.getBytes());
            return new String(base64Encoded);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public String hmacsha1(String message){
        String key = "Ke2TkUq2Jh3Ev16MQL1W3BxOPCW9fBImAomvkZvG";
        Mac hmacSha1;
        byte[] messageBytes = null;
        try {
            byte[] keyBytes = key.getBytes("UTF-8");
            messageBytes = message.getBytes("UTF-8");
            hmacSha1 = Mac.getInstance("HmacSHA1");
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
            hmacSha1.init(secretKey);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        byte[] hashed = hmacSha1.doFinal(messageBytes);
        String result = Base64.getEncoder().encodeToString(hashed);

        return result;
    }

    public String getTime() {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        // 显式设置时区为 GMT
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String formattedDate = dateFormat.format(currentDate);

        return formattedDate;
    }

    public String hqDanXiang() {
        // 获取当前时间戳
        String formattedTime = getTime();

        // 构造消息
//        String message = String.format(
//                "x-date: %s\n" +
//                        "GET\n" +
//                        "\n" +
//                        "/v2/ticket/detail/619dd4d1c156010af50b0e22?levelId&levelType&source=APP&ticketCode",
//                formattedTime
//        );
        String message = "x-date: "+formattedTime+"\n" +
                "GET\n\n\n\n" +
                "/api/isopencaptcha?ticket_id=619dd4d1c156010af50b0e22";

        // 生成签名
        String signature = hmacsha1(message);

        // 构造请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", "hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"" + signature + "\"");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
//        headers.put("Accept", "");

        // 构造请求参数
        Map<String, String> params = new HashMap<>();
        params.put("ticket_id", "619dd4d1c156010af50b0e22");
//        params.put("levelId", "");
//        params.put("ticketCode", "");
//        params.put("source", "APP");

        // 发送请求并获取响应
        String url = "https://gw.app.universalbeijingresort.com/api/isopencaptcha";
        String responseText = OkHttpUtil.get(url,  params, headers);
        // 打印响应
        System.out.println(responseText);

        return responseText;
    }

    /**
     * 下单
     * @param userId
     * @return
     */
    public String order(String userId) {
        String data = "{\n" +
                "  \"cbticket\": \"t03Drl0_YaNBqP79cZCEn9Jsykbvb4aXh3QI5SPbN3Iy1Cnypq4c552muNG6XY07szrL6Wal935LNuwEZqhjvZLzO67kENn8WeK1G5ZdeqG0TFViPu7AfM8qBOHoybIVLITIsfuU9NTCLk*\",\n" +
                "  \"coupon\": [],\n" +
                "  \"data_type\": \"online\",\n" +
                "  \"id\": \"\",\n" +
                "  \"levelId\": \"\",\n" +
                "  \"levelType\": \"\",\n" +
                "  \"price\": \"\",\n" +
                "  \"randstr\": \"@pnX\",\n" +
                "  \"sale_channel\": \"App\",\n" +
                "  \"service_time\": \"\",\n" +
                "  \"source\": \"APP\",\n" +
                "  \"ticket\": [\n" +
                "    {\n" +
                "      \"facility_image\": \"\",\n" +
                "      \"guest_ids\": [\n" +
                "        \"" + userId + "\"\n" +
                "      ],\n" +
                "      \"id\": \"60671ba587f3a44892768777\",\n" +
                "      \"name\": \"环球优速通\",\n" +
                "      \"price\": \"900.00\",\n" +
                "      \"quantity\": \"1\",\n" +
                "      \"ticket_type\": \"Limited Re-Entry\",\n" +
                "      \"visit_end_time\": \"2024-02-24\",\n" +
                "      \"visit_start_time\": \"2024-02-24\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"ticketCode\": \"\",\n" +
                "  \"ticket_id\": \"60671b6e87f3a44892768775\",\n" +
                "  \"total_price\": \"900.00\",\n" +
                "  \"user_info\": {\n" +
                "    \"email\": \"\",\n" +
                "    \"name\": \"\",\n" +
                "    \"phone\": \"\"\n" +
                "  }\n" +
                "}";

        String formattedTime = getTime();
        String md5Data = md5(data);
        String message = String.format("x-date: %s\nPOST\n\napplication/json; charset=UTF-8\n%s\n/v2/order", formattedTime, md5Data);
        String signature = hmacsha1(message);

        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.3.2");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", String.format("hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"%s\"", signature));
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/order";
        String response = OkHttpUtil.post(url, headers, data);
        System.out.println(response);
        return response;
    }

    /**
     * 修改密码发送验证码
     */
    public String operateCode() {
        String formattedTime = getTime();
        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/user/operate_code", formattedTime);
        String signature = hmacsha1(message);

        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", "hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"" + signature + "\"");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/user/operate_code";

        String response = OkHttpUtil.postParamsInPath(url, headers, new HashMap());
        System.out.println(response);
        return response;
    }

    /**
     * 验证验证码
     * @param code
     * @param fid
     * @return
     */
    public String verifyOperateCode(String code, String fid) {
        String formattedTime = getTime();
        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/user/verify_operate_code?code=%s&two_factor_id=%s", formattedTime, code, fid);
        String signature = hmacsha1(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", String.format("hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"%s\"", signature));
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/user/verify_operate_code";
        Map<String, String> params = new HashMap<>();
        params.put("two_factor_id", fid);
        params.put("code", code);

        String response = OkHttpUtil.postParamsInPath(url, headers, params);
        System.out.println(response);
        return response;
    }

    /**
     * 设置新密码
     * @param password
     * @param fid
     * @return
     */
    public String setPwd(String password, String fid) {
        String formattedTime = getTime();
        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/user/change_pwd?new_password=%s&two_factor_id=%s", formattedTime, password, fid);
        String signature = hmacsha1(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", String.format("hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"%s\"", signature));
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/user/change_pwd";
        Map<String, String> params = new HashMap<>();
        params.put("two_factor_id", fid);
        params.put("new_password", password);
        String response = OkHttpUtil.postParamsInPath(url, headers, params);
        System.out.println(response);
        return response;
    }

    /** 登陆相关 **/

    /**
     * 获取指定位随机字符串加数字
     * @param length
     * @return
     */
    public String generateRandomString(int length) {
        // Define a set of characters including uppercase letters, lowercase letters, and digits
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        // Randomly select characters from the set to create the random string of specified length
        StringBuilder randomString = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            randomString.append(characters.charAt(random.nextInt(characters.length())));
        }

        return randomString.toString();
    }

    /**
     * 生成指定位的随机数字字符串
     * @param length
     * @return
     */
    public String generateRandomDigits(int length) {
        // Generate a random string of 10 digits
        StringBuilder randomDigits = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            randomDigits.append(random.nextInt(10));
        }

        return randomDigits.toString();
    }

    /**
     * 发送验证码
     * @param deviceId
     * @param timeStr
     * @param phone
     * @return
     */

    public String sendCode(String deviceId, String timeStr, String phone) {
        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/user/send_code?fid&phone=%s&randstr&region=86&ticket&type=phone_login", timeStr, phone);
        String signature = hmacsha1(message);

        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "");
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceId);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.3.2");
        headers.put("versionCode", "30");
        headers.put("ISDARK", "0");
        headers.put("USERAREA", "other");
        // headers.put("x-date", "Wed, 14 Feb 2024 01:36:57 GMT");
        headers.put("x-date", timeStr);
        headers.put("Authorization", "hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"" + signature + "\"");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/user/send_code?type=phone_login&phone=" + phone + "&region=86&fid=&ticket=&randstr=";

        // Response response = requests.post(url, headers=headers,proxies=proxy);
        String response = OkHttpUtil.postParamsInPath(url, headers, new HashMap());
        return response;
    }

    /**
     * 过滑块发送验证码
     * @param deviceId
     * @param timeStr
     * @param phone
     * @param ticket
     * @param randStr
     * @return
     */

    public String sendImgCode(String deviceId, String timeStr, String phone, String ticket, String randStr) {
        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/user/send_code?fid&phone=%s&randstr=%s&region=86&ticket=%s&type=phone_login", timeStr, phone, randStr, ticket);
        System.out.println(message);
        String signature = hmacsha1(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceId);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("USERAREA", "other");
        headers.put("x-date", timeStr);
        headers.put("Authorization", String.format("hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"%s\"", signature));
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/user/send_code";
        Map<String, String> params = new HashMap<>();
        params.put("type", "phone_login");
        params.put("phone", phone);
        params.put("region", "86");
        params.put("fid", "");
        params.put("ticket", ticket);
        params.put("randstr", randStr);
        String response = OkHttpUtil.postParamsInPath(url, headers, params);
        System.out.println(response);
        return response;
    }

    /**
     * 登陆
     * @param deviceId
     * @param formattedTime
     * @param fid
     * @param phone
     * @param code
     * @return
     */

    public String loginCode(String deviceId, String formattedTime, String fid, String phone, String code) {
        String message = String.format("x-date: %s\nPOST\n\n\n\n/v2/user/login_code?code=%s&fid=%s&phone=%s&region=86&src_type=app&xg_token=%s", formattedTime, code, fid, phone, deviceId);
        String signature = hmacsha1(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceId);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.1.0");
        headers.put("versionCode", "26");
        headers.put("ISDARK", "0");
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", String.format("hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"%s\"", signature));
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/user/login_code";
        Map<String, String> params = new HashMap<>();
        params.put("fid", fid);
        params.put("code", code);
        params.put("src_type", "app");
        params.put("xg_token", deviceId);
        params.put("region", "86");
        params.put("phone", phone);

        String response = OkHttpUtil.postParamsInPath(url, headers, params);
        System.out.println(response);

        return response;
    }

    /**
     * 获取设备信息
     * @return
     */
    public String getDeviceInfo() {
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String[] device = DeviceUtil.getDevice();
        String model = device[0] + " " + device[1];
        Map<String, String> headers = new HashMap<>();
        headers.put("host", "guid.tpns.tencent.com");
        headers.put("Content-Type", "json");
        headers.put("SdkVersion", "1.3.4.3");
        headers.put("AccessId", "1500011295");
// HmacSHA256 update data Utf8:  17078758441500011295{"accessId":1500011295,"accessKey":"A3WGJA3UD0H7","deviceId":"0f993f99f2a6d9a586cf17a73896611f","appCert":"79a9925f3b87db70062cd299bfbbda56","ticket":"","ticketType":-1,"deviceType":0,"deviceInfo":{"imei":"","model":"Pixel 4","os":"android","network":"WIFI","sdDouble":"","resolution":"1080*2214","manu":"Google","apiLevel":"33","sdkVersionName":"13","isRooted":0,"appList":"","cpuInfo":"","language":"zh","timezone":"Asia\/Shanghai","launcherName":"com.android.settings","xgAppList":"","ntfBar":1,"tUinInfo":{"bootTime":"1707549333.518","countryCode":"CN","deviceName":"Pixel 4","carrierInfo":"","memorySize":"5742145536","diskSize":"53684973568","sysFileTime":""},"osVersion":""},"version":4,"keyEncrypted":0,"updateAutoTag":0,"appVersion":"3.3.2","clientid":"","connVersion":0,"channelId":-1,"otherPushTokenOpType":1,"otherPushTokenType":0,"otherPushTokenCrc32":0,"tokenCrc32":0,"otherPushData":"","sdkVersion":"1.3.4.3","appPkgName":"com.ubrmb.app","tAd":0,"hwSdk":0,"cloudVersion":0,"timestamp":1707875844,"register":1,"from":1,"tokenList":[]}
        headers.put("Sign", "YjExMGUwNzk5OGQ5NTBjOWM1NjZkMmJkMmUxODUwY2JjMTM5NDVmNTdhOTQ4Y2MyZDI2Y2I3Zjk3MjUzYzE4Yw==");
        headers.put("TimeStamp", timeStamp);
        headers.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 13; " + model + "Build/TP1A.221005.002.B2)");

        String url = "https://guid.tpns.tencent.com/guid/v4/register_device";
        JSONObject data = new JSONObject();
        data.put("accessId", 1500011295);
        data.put("accessKey", "A3WGJA3UD0H7");
        data.put("deviceId", generateRandomString(32));
        data.put("appCert", generateRandomString(32));
        data.put("ticket", "");
        data.put("ticketType", -1);
        data.put("deviceType", 0);

        JSONObject deviceInfo = new JSONObject();
        deviceInfo.put("imei", "");
        deviceInfo.put("model", model);
        deviceInfo.put("os", "android");
        deviceInfo.put("network", "WIFI");
        deviceInfo.put("sdDouble", "");
        deviceInfo.put("resolution", "1080*2214");
        deviceInfo.put("manu", "HarmonyOS");
        deviceInfo.put("apiLevel", "33");
        deviceInfo.put("sdkVersionName", "13");
        deviceInfo.put("isRooted", 0);
        deviceInfo.put("appList", "");
        deviceInfo.put("cpuInfo", "");
        deviceInfo.put("language", "zh");
        deviceInfo.put("timezone", "Asia/Shanghai");
        deviceInfo.put("launcherName", "com.android.settings");
        deviceInfo.put("xgAppList", "");
        deviceInfo.put("ntfBar", 1);

        JSONObject tUinInfo = new JSONObject();
        tUinInfo.put("bootTime", timeStamp + ".518");
        tUinInfo.put("countryCode", "CN");
        tUinInfo.put("deviceName", model);
        tUinInfo.put("carrierInfo", "");
        tUinInfo.put("memorySize", generateRandomDigits(10));
        tUinInfo.put("diskSize", generateRandomDigits(11));
        tUinInfo.put("sysFileTime", "");

        deviceInfo.put("tUinInfo", tUinInfo);
        deviceInfo.put("osVersion", "");

        data.put("deviceInfo", deviceInfo);
        data.put("version", 4);
        data.put("keyEncrypted", 0);
        data.put("updateAutoTag", 0);
        data.put("appVersion", "3.3.2");
        data.put("clientid", "");
        data.put("connVersion", 0);
        data.put("channelId", -1);
        data.put("otherPushTokenOpType", 1);
        data.put("otherPushTokenType", 0);
        data.put("otherPushTokenCrc32", 0);
        data.put("tokenCrc32", 0);
        data.put("otherPushData", "");
        data.put("sdkVersion", "1.3.4.3");
        data.put("appPkgName", "com.ubrmb.app");
        data.put("tAd", 0);
        data.put("hwSdk", 0);
        data.put("cloudVersion", 0);
        data.put("timestamp", Long.valueOf(timeStamp));
        data.put("register", 1);
        data.put("from", 1);
        data.put("tokenList", new ArrayList<>());
        String jsonData = data.toString();
        String response = OkHttpUtil.post(url, headers, jsonData);
        System.out.println(response);
        return response;
    }

    /**
     * 获取sdk
     * @param appid
     * @param openid
     * @param outTradeNo
     * @return
     */

    public String openSave(String appid, String openid, String outTradeNo) {
        String msg = "app_pkg_name=com.ubrmb.app&app_sign=77c242fbf4a2a93ee3e6b8dec5ebd604&openid=" + openid + "&out_trade_no=" + outTradeNo + "&pay_method=open_alipay:6&sdkversion=2.0.1&firstrequest=1";
        String encryptMsg = aesEncrypt(msg, "77FBC4FBC28E692C950C8CFFD423071A", "1234567890123456");
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept-Charset", "UTF-8");
        headers.put("Host", "billing.app.universalbeijingresort.com");
        headers.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 13; Pixel 4 Build/TP1A.221005.002.B2)");
        headers.put("Accept", "");

        String url = "https://billing.app.universalbeijingresort.com/api/v1/r/" + appid + "/open_save";
        Map<String, String> data = new HashMap<>();
        data.put("encrypt_msg", encryptMsg);
        data.put("key_time", "1708414445");
        data.put("openid", openid);
        data.put("msg_len", "180");
        data.put("offer_id", appid);
        data.put("key_len", "newkey");

        System.out.println(data);
        String response = OkHttpUtil.post(url, headers, data);

        System.out.println(response);
        return response;
    }

    /**
     * 查单
     */

    public String payment(String oid) {
        String formattedTime = getTime();
        String message = String.format("x-date: %s\nPUT\n\napplication/json; charset=UTF-8\n\n/v2/order/payment/%s", formattedTime, oid);
        String signature = hmacsha1(message);

        Map<String, String> headers = new HashMap<>();
        headers.put("lat", "");
        headers.put("lng", "");
        headers.put("language", "ch");
        headers.put("deviceid", deviceid);
        headers.put("IsInPark", "0");
        headers.put("OS", "Android");
        headers.put("PreSaleSign", "0");
        headers.put("appVersion", "3.3.2");
        headers.put("versionCode", "30");
        headers.put("ISDARK", "0");
        headers.put("APPToken", APPToken);
        headers.put("USERAREA", "other");
        headers.put("x-date", formattedTime);
        headers.put("Authorization", "hmac id=\"APID8jN115a8pHemP3wdo8d65su943JGe5vl68r4\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\"" + signature + "\"");
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("Host", "gw.app.universalbeijingresort.com");
        headers.put("User-Agent", "okhttp/3.12.1");
        headers.put("Accept", "");

        String url = "https://gw.app.universalbeijingresort.com/v2/order/payment/" + oid;

        JSONObject data = new JSONObject();
        data.put("pay_type", "ALIPAY");

        String response = OkHttpUtil.put(url, headers, data.toString());
        System.out.println(response);
        return response;
    }


    public static String aesDecrypt(String data, String key, String iv) {
        byte[] dataBytes = hexStringToByteArray(data);
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] decryptedBytes = cipher.doFinal(dataBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aesEncrypt(String data, String key, String iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            byte[] paddedData = padString(data).getBytes(StandardCharsets.UTF_8);
            byte[] encryptedBytes = cipher.doFinal(paddedData);
            return byteArrayToHexString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String padString(String data) {
        int padding = 16 - (data.length() % 16);
        char paddingChar = (char) padding;
        StringBuilder paddedData = new StringBuilder(data);
        for (int i = 0; i < padding; i++) {
            paddedData.append(paddingChar);
        }
        return paddedData.toString();
    }

    private static byte[] hexStringToByteArray(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            bytes[i / 2] = (byte) Integer.parseInt(hexString.substring(i, i + 2), 16);
        }
        return bytes;
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02X", b));
        }
        return hexString.toString();
    }

}
